//
//  BaseService.m
//  Baseproject
//
//  Created by gullmei on 15/9/11.
//  Copyright (c) 2015年 黄定坤. All rights reserved.
//

#import "BaseService.h"
#import  "BaseModel.h"
#import "TypeConversion.h"
//#import  "UserModel.h"
@implementation ResResult

- (id)init {
    self = [super init];
    if (self) {
        _resData = nil;
        _resCode = -1;
        _errMessage = @"";
    }
    
    return self;
}
@end


@implementation BaseService
@synthesize delegate;
@synthesize hostUrl = _hostUrl, paramDict = _paramDict,modelclass   = _modelclass, sign = _sign,notificationName = _notificationName,reponseType = _reponseType, httpRequestResultBlock,saveToGlobalData,decodeData;

-(id)init
{
    if(self = [super init]){
      
        _paramDict = [[NSDictionary alloc] init];
        _reponseType = TYPE_OBJECT;
        _hostUrl =@"192.168.1.208/DMIS";
    }
    
        return self;
}

+ (instancetype)getObject
{
    BaseService *base = [[BaseService alloc] init];
    return base;
}

- (void)postRequestWithUrl:(NSString *)urlString parameter:(id)param success:(id (^)(id, NSError *))aSuccess
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    [manager setRequestSerializer: [AFJSONRequestSerializer serializer]];
//    [manager setResponseSerializer: [AFJSONResponseSerializer serializer]];
//    
     urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager POST:urlString parameters:param success:^void(AFHTTPRequestOperation * request, id object) {
        
        NSString *responseString = [[NSString alloc] initWithData:object encoding:NSUTF8StringEncoding];
        NSData *data;
        id responseObject = nil;
        NSError *serializationError = nil;
        data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
       
        responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&serializationError];
//        int  code =[[responseObject  objectForKey:@"retCode"] intValue] ;
        int  code = 1;
        [self OnRecvData:responseObject rcode:code];
        
      
    } failure:^void(AFHTTPRequestOperation * request, NSError *error) {
        
        //success324617
        [self OnRecvData:nil rcode:NET_ERROR];

    }];
}
#pragma mark - OnRecvData  接受回报处理流程
-(void)OnRecvData:(id)responseObject rcode:(int)code
{
    @try {
        id resultobject;
        if(code == 1) //返回正常
        {
            if(self.decodeData)
            {
                resultobject = self.decodeData(responseObject);
            }
            else if(_reponseType == TYPE_ARRAY)
            {
    
                //NSArray * array  = [responseObject objectForKey:@"ScheduleInfo"] ;
                NSArray * array  = [responseObject objectForKey:self.keyStr] ;
                NSMutableArray * list = [[NSMutableArray alloc] init ];
                //TODOWORK:打印JSONModelT
                [BaseModel printModel:[array objectAtIndex:0]];
                for ( NSDictionary*   dic in array)
                {
                    //TODOWORK: 
                    BaseModel * model = [_modelclass decodeAndSaveData:dic];
                    [list addObject:model];
                }
                resultobject = list;
            }else
            {
                //NSDictionary * dic  = [responseObject objectForKey:@"result"];
                NSDictionary * dic = responseObject;
    
                [BaseModel printModel:dic];
                
                BaseModel * model = [_modelclass decodeAndSaveData:dic];
                
                
                resultobject = model;
            }
            
        }else if(code != NET_ERROR)
        {
            NSString * expTips = [responseObject objectForKey:@"res"];
            resultobject = expTips;
        }else
        {
            resultobject = [responseObject objectForKey:@"message"];
    
        }
        
        if(self.saveToGlobalData)
        {
            self.saveToGlobalData(resultobject,code);
        }
        
        
        //success
        if (self.delegate && [self.delegate respondsToSelector:@selector(responseWithObject:resultCode:error:)]) {
            [self.delegate responseWithObject:resultobject resultCode:code error:nil];
        } else {
            ResResult * rdata = [[ResResult alloc] init];
            rdata.resData = resultobject;
            rdata.resCode = code;
            [[NSNotificationCenter defaultCenter] postNotificationName:self.notificationName object:rdata];
        }
        
        if(self.httpRequestResultBlock)
        {
            self.httpRequestResultBlock(resultobject ,code);
        }
    }
    @catch (NSException *exception) {
        
        NSLog(@"%@",@"程序崩了，请检查OnRecvData:(id)responseObject rcode:(int)code");
    }
    @finally {
        
    }

}
#pragma mark - start  启动业务
#pragma mark -
-(void)startPostRequest
{
    [self postRequestWithUrl:_hostUrl parameter:_paramDict success:^id(id responseObject, NSError *error) {
      
        return nil;
    }];

}
#pragma mark - md5加密  启动业务
#pragma mark -
+ (NSString *)md5HexDigest:(NSString*)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];//
    
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

@end
